package com.codepoorfish.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.codepoorfish.anno.UserLoginToken;
import com.codepoorfish.controller.utils.R;
import com.codepoorfish.domain.Task;
import com.codepoorfish.service.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/tasks")
public class TaskController {
    @Autowired
    private TaskService taskService;

    // RestFul风格获取所有
    @UserLoginToken
    @GetMapping
    public R getTasks() {
        List<Task> tasks = taskService.list();
        if (tasks == null) {
            return new R(false, "数据查找失败！");
        } else
            return new R(true, tasks);
    }

    // RestFul风格根据任务Id查询
    @GetMapping("/{id}")
    @UserLoginToken
    public R getTaskById(@PathVariable("id") Integer id) {
        Task task = taskService.getById(id);
        if (task == null) {
            return new R(false, "数据查找失败！");
        } else
            return new R(true, task);
    }

    // RestFul风格根据任务Id删除数据
    @DeleteMapping("/{id}")
    @UserLoginToken
    public R deleteTaskById(@PathVariable("id") Integer id) {
        return new R(taskService.removeById(id));
    }


    @DeleteMapping("/deleteBatch")
    @UserLoginToken
    public R deleteListTask(@RequestBody List<String> ids) {
        return new R(taskService.removeByIds(ids));
    }

    // RestFul风格更新数据，参数为实体
    @PutMapping
    @UserLoginToken
    public R updateTask(@RequestBody Task task) {
        return new R(taskService.updateById(task));
    }

    @PutMapping("/updateBatch")
    @UserLoginToken
    public R updateListTask(@RequestBody List<Task> taskList) {
        return new R(taskService.updateBatchById(taskList));
    }

    // RestFul风格新增数据
    @PostMapping
    @UserLoginToken
    public R saveTask(@RequestBody Task task) {
        return new R(taskService.save(task));
    }

    //RestFul风格实现分页查询
    @GetMapping("/{page}/{size}")
    @UserLoginToken
    public R getTaskPage(@PathVariable("page") Integer page, @PathVariable("size") Integer size) {
        return new R(true, taskService.getTaskByPage(page, size));
    }

    //RestFul风格实现按照flag字段查询
    @GetMapping("/finish")
    @UserLoginToken
    public R getFinishTask(@RequestParam String username) {
        List<Task> tasks = taskService.list(new QueryWrapper<Task>().eq("flag", true).eq("user_name", username));
        return new R(true, tasks);
    }

    @GetMapping("/unfinish")
    @UserLoginToken
    public R getUnFinishTask(@RequestParam String username) {
        List<Task> tasks = taskService.list(new QueryWrapper<Task>().eq("flag", false).eq("user_name", username));
        return new R(true, tasks);
    }
}
